const { src, dest, series, parallel, watch } = require("gulp");
//src dest解构
const sass = require("gulp-sass");//使用sass
const webpack = require("webpack-stream");//打包js
const rev = require("gulp-rev");//生成rev文件夹，重命名文件
const revCollector = require("gulp-rev-collector");//重命名的js文件名字同步到html文件

function copyHTML() {
    return src("./src/*.html")
        .pipe(dest('./dist/'));
}

function copyImages() {
    return src('./src/img/*.*')
        .pipe(dest('./dist/img'));
}
function copyLib() {
    return src('./src/lib/*.*')
        .pipe(dest('./dist/js/lib'));
}

function compileCss() {
    return src('./src/style/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(rev())
        .pipe(dest("./dist/style/"))
        .pipe(rev.manifest("css-manifest.json"))
        .pipe(dest("./rev/"))
}

function compileJS() {
    return webpack({
        mode: "production",
        entry: './src/app.js',
        output: {
            filename: 'app.min.js'
        },
        module: {
            rules: [
                {
                    test: /\js$/,//匹配所有js
                    exclude: /(node_modules)/,//排除node-modules中的文件
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                            plugins: ['@babel/plugin-transform-runtime']
                        }
                    }
                },
                {//template渲染页面时用到
                    test: /\.html$/,
                    loader: "string-loader"
                }
            ]
        }
    })
        .pipe(rev())
        .pipe(dest("./dist/js/"))
        .pipe(rev.manifest("js-manifest.json"))
        .pipe(dest('./rev/'))
}

function revCol() {
    return src(['./rev/*.json', './dist/*.html'])
        .pipe(revCollector({
            replaceReved: true
        }))
        .pipe(dest('./dist/'))
}


function copyFonts() {
    return src('./src/style/fonts/*.*')
        .pipe(dest('./dist/style/fonts/'));
}

exports.default = series(parallel(compileJS, compileCss, copyHTML, copyImages, copyFonts, copyLib), revCol);